package com.ste.server;

import java.util.regex.Pattern;

import com.ste.domain.OrderBook;
import com.ste.server.command.Command;
import com.ste.server.command.Logon;
import com.ste.server.command.Trade;
import com.ste.server.command.TradeWithFixPrice;
import com.ste.server.command.TradeWithMarketPrice;

public class CommandHandler implements Runnable {

	private Server server;

	public CommandHandler(Server server) {
		this.server = server;
	}

	@Override
	public void run() {
		Command command = null;
		while (true) {
			try {
				command = server.getMessageQueue().take();
				execute(command);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

	private void execute(Command command) {
		if (Pattern.matches(Logon.regexp, command.getMessage())) {
			String result = new Logon(server, command).execute();
			command.getClient().sendMessage(result);
		} else if (Pattern.matches(TradeWithFixPrice.regexp, command.getMessage())) {
			try {
				Trade trade = new TradeWithFixPrice(server, command);
				trade.execute();
			} catch (NumberFormatException e) {
				command.getClient().sendMessage(String.format(OrderBook.REJECT, e.getMessage()));
			}
		} else if (Pattern.matches(TradeWithMarketPrice.regexp, command.getMessage())) {
			try {
				Trade trade = new TradeWithMarketPrice(server, command);
				trade.execute();
			} catch (NumberFormatException e) {
				command.getClient().sendMessage(String.format(OrderBook.REJECT, e.getMessage()));
			}
		}

	}
}
